﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for Common
/// </summary>
public class Common
{
    //-- Encrypt & Decrypt
    //--
    public static readonly string PasswordHash = "P@@Sw0rd";
    public static readonly string SaltKey = "S@LT&KEY";
    public static readonly string VIKey = "@1B2c3D4e5F6g7H8";

    public Common()
    {

    }

    /// <summary>
    /// Calculate md5 hash password
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string CalculateMd5Hash(string input)
    {
        // Step 1: calculate md5 hash from input string
        var md5 = System.Security.Cryptography.MD5.Create();
        var inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        var hash = md5.ComputeHash(inputBytes);

        // Step 2: convert byte array to hex string
        var stringBuilder = new StringBuilder();
        for (var i = 0; i < hash.Length; i++)
        {
            stringBuilder.Append(hash[i].ToString("X2"));
        }
        return stringBuilder.ToString();
    }
    
    /// <summary>
    /// Sử dụng để Convert Chữ Số Có Dấu sang Số Không Dấu có gạch ở giữa(Dùng ASCII)
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string ConvertToUnSign(string text)
    {

        for (var i = 33; i < 48; i++)
        {
            text = text.Replace(((char)i).ToString(CultureInfo.InvariantCulture), "");

        }

        for (var i = 58; i < 65; i++)
        {
            text = text.Replace(((char)i).ToString(CultureInfo.InvariantCulture), "");

        }

        for (var i = 91; i < 97; i++)
        {
            text = text.Replace(((char)i).ToString(CultureInfo.InvariantCulture), "");
        }

        for (var i = 123; i < 127; i++)
        {
            text = text.Replace(((char)i).ToString(CultureInfo.InvariantCulture), "");
        }
        text = text.ToLower();
        text = text.Replace(" ", "-");
        var regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
        var strFormD = text.Normalize(System.Text.NormalizationForm.FormD);
        return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
    }

    /// <summary>
    /// Phuong thuc dung de ma hoa
    /// </summary>
    /// <param name="plainText"></param>
    /// <returns></returns>
    public static string Encrypt(string plainText)
    {
        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        var keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
        var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

        byte[] cipherTextBytes;

        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                cipherTextBytes = memoryStream.ToArray();
                cryptoStream.Close();
            }
            memoryStream.Close();
        }
        return Convert.ToBase64String(cipherTextBytes);
    }

    /// <summary>
    /// Phuong thuc dung de giai ma cai da ma hoa
    /// </summary>
    /// <param name="encryptedText"></param>
    /// <returns></returns>
    public static string Decrypt(string encryptedText)
    {
        var cipherTextBytes = Convert.FromBase64String(encryptedText);
        var keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.None };

        var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
        var memoryStream = new MemoryStream(cipherTextBytes);
        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        var plainTextBytes = new byte[cipherTextBytes.Length];

        var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    }

    /// <summary>
    /// Convert datetime to format ddMMyyyyHHmmss 
    /// </summary>
    /// <returns>string</returns>
    public static string ConvertDateTimetoString()
    {
        var dateTime = DateTime.Now;        
        return dateTime.ToString("ddMMyyyyHHmmss");
    }

}